require.config({ paths: { 'vs': '../node_modules/monaco-editor/min/vs' } });
require(['vs/editor/editor.main'], function () {

    let editor;
    let currentLanguage = 'javascript';
    function getUserId() {
        const el = document.getElementById('workspace-userid');
        return (el && el.value) ? el.value.trim() : 'test-user';
    }

    // 操作记录数组
    let actionLog = [];

    // 添加操作记录的函数
    function addActionLog(action) {
        const now = new Date();
        const timestamp = now.getFullYear() + '-' + 
                         String(now.getMonth() + 1).padStart(2, '0') + '-' + 
                         String(now.getDate()).padStart(2, '0') + ' ' +
                         String(now.getHours()).padStart(2, '0') + ':' +
                         String(now.getMinutes()).padStart(2, '0') + ':' +
                         String(now.getSeconds()).padStart(2, '0');
        
        const logEntry = {
            action: action,
            timestamp: timestamp
        };
        
        actionLog.push(logEntry);
        updateActionLogDisplay();
        
        // 限制记录数量，最多显示50条
        if (actionLog.length > 50) {
            actionLog = actionLog.slice(-50);
        }
    }

    // 更新操作记录显示
    function updateActionLogDisplay() {
        const logContainer = document.getElementById('user-action-log');
        if (!logContainer) return;
        
        logContainer.innerHTML = actionLog.map(entry => 
            `<div class="log-entry">
                <span class="log-action">${entry.action}</span>
                <span class="log-timestamp">${entry.timestamp}</span>
            </div>`
        ).join('');
        
        // 自动滚动到底部
        logContainer.scrollTop = logContainer.scrollHeight;
    }

    // ============ 文件树/工作空间 ============
    let currentOpenedFile = null; // 容器内完整路径
    let currentSelectedPath = null; // 选中的路径（文件或目录）
    let currentSelectedIsDir = false;

    async function fetchJson(url, options = {}) {
        const res = await fetch(url, options);
        if (!res.ok) throw new Error('请求失败: ' + res.status);
        const ct = res.headers.get('content-type') || '';
        if (ct.includes('application/json')) return res.json();
        return res.text();
    }

    async function loadFileTree() {
        const root = document.getElementById('workspace-root').value || '/home/coder/project';
        const currentUserId = getUserId();
        addActionLog(`加载文件树: ${root} (用户: ${currentUserId})`);
        const container = document.getElementById('file-tree');
        if (container) container.innerHTML = '<div style="color:#666;font-size:12px;padding:8px;">加载中...</div>';
        try {
            const tree = await fetchJson(`/api/user-files/${currentUserId}/tree?rootDirectory=${encodeURIComponent(root)}`);
            renderFileTree(Array.isArray(tree) ? tree : [], root);
            if (Array.isArray(tree) && tree.length === 0) {
                if (container) container.innerHTML = '<div style="color:#999;font-size:12px;padding:8px;">未获取到目录。请确认 IDE 容器 ide-' + currentUserId + ' 正在运行，且路径存在。</div>';
            }
        } catch (e) {
            if (container) container.innerHTML = '<div style="color:#c00;font-size:12px;padding:8px;">加载失败：' + e.message + '</div>';
            addActionLog('加载文件树失败：' + e.message);
        }
    }

    function renderFileTree(nodes, root) {
        const container = document.getElementById('file-tree');
        if (!container) return;
        container.innerHTML = '';
        const ul = document.createElement('div');
        ul.className = 'tree-root';
        nodes.forEach(n => ul.appendChild(renderTreeNode(n)));
        container.appendChild(ul);
    }

    // ============ 语言推断与切换 ============
    function getFileExtension(filePath) {
        const name = (filePath || '').split('/').pop();
        const idx = name.lastIndexOf('.');
        if (idx === -1) return '';
        return name.substring(idx + 1).toLowerCase();
    }

    function inferLanguageByFilename(filePath) {
        const ext = getFileExtension(filePath);
        switch (ext) {
            case 'js':
            case 'mjs':
            case 'cjs':
            case 'jsx':
                return 'javascript';
            case 'ts':
            case 'tsx':
                return 'typescript';
            case 'java':
                return 'java';
            case 'cpp':
            case 'cc':
            case 'cxx':
            case 'hpp':
            case 'hh':
            case 'hxx':
                return 'cpp';
            case 'go':
                return 'go';
            case 'rs':
                return 'rust';
            case 'py':
                return 'python';
            case 'cs':
                return 'csharp';
            case 'php':
                return 'php';
            case 'rb':
                return 'ruby';
            case 'swift':
                return 'swift';
            case 'kt':
            case 'kts':
                return 'kotlin';
            case 'html':
            case 'htm':
                return 'html';
            case 'css':
            case 'scss':
            case 'less':
                return 'css';
            case 'json':
                return 'json';
            case 'xml':
            case 'xsd':
            case 'xslt':
                return 'xml';
            case 'yml':
            case 'yaml':
                return 'yaml';
            case 'md':
            case 'markdown':
                return 'markdown';
            case 'sh':
            case 'bash':
                return 'shell';
            case 'sql':
                return 'sql';
            default:
                return '';
        }
    }

    function setEditorLanguageIfAvailable(lang) {
        if (!lang) return false;
        const select = document.getElementById('language-select');
        if (!select) return false;
        const hasOption = Array.from(select.options).some(o => o.value === lang);
        if (!hasOption) return false;
        // 切换选择器与编辑器语言
        select.value = lang;
        currentLanguage = lang;
        if (editor && editor.getModel()) {
            monaco.editor.setModelLanguage(editor.getModel(), lang);
        }
        return true;
    }

    function renderTreeNode(node) {
        const el = document.createElement('div');
        el.className = 'tree-item';
        el.dataset.path = node.path;
        el.dataset.dir = node.directory ? '1' : '0';
        const icon = document.createElement('span');
        icon.className = 'icon';
        icon.textContent = node.directory ? '📁' : '📄';
        const name = document.createElement('span');
        name.className = 'name';
        name.textContent = node.name;
        el.appendChild(icon);
        el.appendChild(name);

        el.onclick = () => onTreeItemClick(node);

        if (node.children && node.children.length) {
            const children = document.createElement('div');
            children.className = 'tree-children';
            node.children.forEach(c => children.appendChild(renderTreeNode(c)));
            el.appendChild(children);
        }
        return el;
    }

    async function onTreeItemClick(node) {
        document.querySelectorAll('.tree-item.active').forEach(x => x.classList.remove('active'));
        const item = document.querySelector(`.tree-item[data-path="${CSS.escape(node.path)}"]`);
        if (item) item.classList.add('active');
        currentSelectedPath = node.path;
        currentSelectedIsDir = !!node.directory;
        if (!node.directory) {
            await openFile(node.path);
        }
    }

    async function openFile(path) {
        addActionLog(`打开文件：${path}`);
        const currentUserId = getUserId();
        const content = await fetchJson(`/api/user-files/${currentUserId}/file?filePath=${encodeURIComponent(path)}`);
        if (typeof content === 'string') {
            editor.setValue(content);
        } else {
            // 兼容部分返回json的情况
            editor.setValue(content.content || '');
        }
        currentOpenedFile = path;

        // 根据文件类型自动切换语言
        const inferred = inferLanguageByFilename(path);
        if (setEditorLanguageIfAvailable(inferred)) {
            addActionLog(`根据文件类型自动切换语言为：${inferred}`);
        }
    }

    async function saveCurrentFile() {
        if (!currentOpenedFile) {
            alert('请先打开一个文件');
            return;
        }
        const content = editor.getValue();
        const currentUserId = getUserId();
        const res = await fetchJson(`/api/user-files/${currentUserId}/save?filePath=${encodeURIComponent(currentOpenedFile)}`, {
            method: 'POST',
            headers: { 'Content-Type': 'text/plain;charset=UTF-8' },
            body: content
        });
        if (typeof res === 'object' && res && res.success === false) {
            alert('保存失败，请确认 IDE 容器正在运行且路径可写');
            addActionLog(`保存失败：${currentOpenedFile}`);
        } else {
            addActionLog(`保存文件：${currentOpenedFile}`);
        }
    }

    async function createFileAt(path) {
        const name = prompt('新建文件名，例如 main.py');
        if (!name) return;
        const base = (currentSelectedPath && currentSelectedIsDir) ? currentSelectedPath : path;
        const full = (base.endsWith('/') ? base : base + '/') + name;
        const currentUserId = getUserId();
        try {
            const res = await fetchJson(`/api/user-files/${currentUserId}/create-file?filePath=${encodeURIComponent(full)}`, { method: 'POST' });
            if (typeof res === 'object' && res && res.success === false) {
                alert('新建文件失败：请确认 IDE 容器 ide-' + currentUserId + ' 正在运行，且路径存在/可写');
                addActionLog(`新建文件失败：${full}`);
                return;
            }
            addActionLog(`新建文件：${full}`);
        } catch (e) {
            console.error(e);
            alert('新建文件失败：网络或服务异常');
            addActionLog(`新建文件失败：${full}`);
            return;
        }
        await loadFileTree();
    }

    async function createFolderAt(path) {
        const name = prompt('新建文件夹名，例如 src');
        if (!name) return;
        const base = (currentSelectedPath && currentSelectedIsDir) ? currentSelectedPath : path;
        const full = (base.endsWith('/') ? base : base + '/') + name;
        const currentUserId = getUserId();
        try {
            const res = await fetchJson(`/api/user-files/${currentUserId}/create-directory?dirPath=${encodeURIComponent(full)}`, { method: 'POST' });
            if (typeof res === 'object' && res && res.success === false) {
                alert('新建文件夹失败：请确认 IDE 容器 ide-' + currentUserId + ' 正在运行，且路径存在/可写');
                addActionLog(`新建文件夹失败：${full}`);
                return;
            }
            addActionLog(`新建文件夹：${full}`);
        } catch (e) {
            console.error(e);
            alert('新建文件夹失败：网络或服务异常');
            addActionLog(`新建文件夹失败：${full}`);
            return;
        }
        await loadFileTree();
    }

    async function deletePathAt(path) {
        if (!confirm(`确定删除：${path} ？`)) return;
        const currentUserId = getUserId();
        try {
            const res = await fetchJson(`/api/user-files/${currentUserId}/delete?path=${encodeURIComponent(path)}&recursive=true`, { method: 'DELETE' });
            if (typeof res === 'object' && res && res.success === false) {
                alert('删除失败：请确认 IDE 容器 ide-' + currentUserId + ' 正在运行，且路径存在/可写');
                addActionLog(`删除失败：${path}`);
                return;
            }
            addActionLog(`删除：${path}`);
        } catch (e) {
            console.error(e);
            alert('删除失败：网络或服务异常');
            addActionLog(`删除失败：${path}`);
            return;
        }
        await loadFileTree();
    }

    // 详细示例代码（用于代码执行）
    const detailedExamples = {
        'python': `# Python 示例
print("Hello, World! 我是Python！")

def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

for i in range(10):
    print(f"fibonacci({i}) = {fibonacci(i)}")`,

        'java': `// Java 示例
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, World! 我是Java！");
        
        for (int i = 0; i < 10; i++) {
            System.out.println("fibonacci(" + i + ") = " + fibonacci(i));
        }
    }
    
    public static int fibonacci(int n) {
        if (n <= 1) return n;
        return fibonacci(n-1) + fibonacci(n-2);
    }
}`,

        'cpp': `// C++ 示例
#include <iostream>
using namespace std;

int fibonacci(int n) {
    if (n <= 1) return n;
    return fibonacci(n-1) + fibonacci(n-2);
}

int main() {
    cout << "Hello, World! 我是c++!" << endl;
    
    for (int i = 0; i < 10; i++) {
        cout << "fibonacci(" << i << ") = " << fibonacci(i) << endl;
    }
    
    return 0;
}`,

        'javascript': `// JavaScript 示例
console.log("Hello, World! 我是JavaScript！");

function fibonacci(n) {
    if (n <= 1) return n;
    return fibonacci(n-1) + fibonacci(n-2);
}

for (let i = 0; i < 10; i++) {
    console.log(\`fibonacci(\${i}) = \${fibonacci(i)}\`);
}`,

        'go': `// Go 示例
package main

import "fmt"

func fibonacci(n int) int {
    if n <= 1 {
        return n
    }
    return fibonacci(n-1) + fibonacci(n-2)
}

func main() {
    fmt.Println("Hello, World! 我是go !")
    
    for i := 0; i < 10; i++ {
        fmt.Printf("fibonacci(%d) = %d\\n", i, fibonacci(i))
    }
}`,

        'rust': `// Rust 示例
fn fibonacci(n: u32) -> u32 {
    match n {
        0 => 0,
        1 => 1,
        _ => fibonacci(n - 1) + fibonacci(n - 2),
    }
}

fn main() {
    println!("Hello, World! 我是rust ！");
    
    for i in 0..10 {
        println!("fibonacci({}) = {}", i, fibonacci(i));
    }
}`
    };

    // 初始化编辑器
    function initEditor() {
        console.log('开始初始化编辑器...');
        
        try {
            // 默认使用深色主题
            monaco.editor.setTheme('vs-dark');
            console.log('主题设置完成: vs-dark');

            const container = document.getElementById('editor-container');
            if (!container) {
                console.error('未找到编辑器容器元素');
                return;
            }
            console.log('找到编辑器容器:', container);

            editor = monaco.editor.create(container, {
                value: detailedExamples['javascript'],
                language: 'javascript',
                theme: 'vs-dark',
                fontSize: 14,
                lineNumbers: 'on',
                automaticLayout: true
            });
            console.log('Monaco Editor 创建成功:', editor);

            bindEvents();
            updateInfo();
            addActionLog('Monaco Editor 初始化完成');
            console.log('编辑器初始化完成');
        } catch (error) {
            console.error('编辑器初始化失败:', error);
        }
    }

    // 绑定事件
    function bindEvents() {
        console.log('开始绑定事件...');
        
        // 语言选择
        const languageSelect = document.getElementById('language-select');
        if (languageSelect) {
            languageSelect.onchange = function(e) {
                currentLanguage = e.target.value;
                console.log('语言切换为:', currentLanguage);
                addActionLog(`切换编程语言为：${e.target.options[e.target.selectedIndex].text}`);
                if (editor && editor.getModel()) {
                    monaco.editor.setModelLanguage(editor.getModel(), currentLanguage);
                }
            };
        }

        // 主题选择
        const themeSelect = document.getElementById('theme-select');
        if (themeSelect) {
            themeSelect.onchange = function(e) {
                const selectedTheme = e.target.value;
                console.log('主题切换为:', selectedTheme);
                addActionLog(`切换主题为：${e.target.options[e.target.selectedIndex].text}`);
                if (editor) {
                    monaco.editor.setTheme(selectedTheme);
                }
            };
            // 默认选中 vs-dark
            themeSelect.value = 'vs-dark';
        }

        // 内置终端已回退

        // 获取内容按钮
        const getContentBtn = document.getElementById('get-content-btn');
        if (getContentBtn) {
            getContentBtn.onclick = function() {
                console.log('点击获取内容按钮');
                addActionLog('点击了获取代码内容按钮');
                if (editor) {
                    const content = editor.getValue();
                    document.getElementById('content-display').value = content;
                }
            };
        }

        // 清空内容按钮
        const clearContentBtn = document.getElementById('clear-content-btn');
        if (clearContentBtn) {
            clearContentBtn.onclick = function() {
                console.log('点击清空内容按钮');
                addActionLog('点击了清空内容按钮');
                if (confirm('清空内容？')) {
                    editor.setValue('');
                    addActionLog('清空了编辑器内容');
                }
            };
        }


        // 代码执行相关事件绑定
        const runCodeBtn = document.getElementById('run-code-btn');
        if (runCodeBtn) {
            console.log('绑定运行代码按钮事件');
            runCodeBtn.onclick = function() {
                console.log('点击运行代码按钮');
                addActionLog('点击了运行代码按钮');
                runCode();
            };
        } else {
            console.error('未找到运行代码按钮');
        }

        const loadExampleBtn = document.getElementById('load-example-btn');
        if (loadExampleBtn) {
            console.log('绑定加载示例按钮事件');
            loadExampleBtn.onclick = function() {
                console.log('点击加载示例按钮');
                addActionLog('点击了加载示例按钮');
                loadDetailedExample();
            };
        } else {
            console.error('未找到加载示例按钮');
        }

        const clearResultBtn = document.getElementById('clear-result-btn');
        if (clearResultBtn) {
            console.log('绑定清空结果按钮事件');
            clearResultBtn.onclick = function() {
                console.log('点击清空结果按钮');
                addActionLog('点击了清空结果按钮');
                clearExecutionResult();
            };
        } else {
            console.error('未找到清空结果按钮');
        }

        // 文件树按钮
        const refreshBtn = document.getElementById('refresh-tree-btn');
        if (refreshBtn) refreshBtn.onclick = () => loadFileTree();
        const saveBtn = document.getElementById('save-file-btn');
        if (saveBtn) saveBtn.onclick = () => saveCurrentFile();
        const newFileBtn = document.getElementById('new-file-btn');
        if (newFileBtn) newFileBtn.onclick = async () => {
            const root = document.getElementById('workspace-root').value || '/home/coder/project';
            await createFileAt(root);
        };
        const newFolderBtn = document.getElementById('new-folder-btn');
        if (newFolderBtn) newFolderBtn.onclick = async () => {
            const root = document.getElementById('workspace-root').value || '/home/coder/project';
            await createFolderAt(root);
        };
        const deleteBtn = document.getElementById('delete-path-btn');
        if (deleteBtn) deleteBtn.onclick = async () => {
            const root = document.getElementById('workspace-root').value || '/home/coder/project';
            const target = currentSelectedPath || currentOpenedFile || root;
            await deletePathAt(target);
        };

        if (editor) {
            editor.onDidChangeCursorPosition(function(e) {
                updateCursorInfo(e.position);
            });

            editor.onDidChangeModelContent(function() {
                updateInfo();
                // 记录内容变化（但限制频率，避免过多记录）
                const currentTime = Date.now();
                if (!editor.lastContentChangeTime || currentTime - editor.lastContentChangeTime > 2000) {
                    const content = editor.getValue();
                    if (content.trim()) {
                        const preview = content.length > 50 ? content.substring(0, 50) + '...' : content;
                        addActionLog(`输入了内容：${preview}`);
                    }
                    editor.lastContentChangeTime = currentTime;
                }
            });
        }
        
        console.log('事件绑定完成');
    }

    // 更新光标信息
    function updateCursorInfo(position) {
        document.getElementById('line-number').textContent = position.lineNumber;
        document.getElementById('column-number').textContent = position.column;
        const offset = editor.getModel().getOffsetAt(position);
        document.getElementById('char-position').textContent = offset;
    }

    // 更新信息显示
    function updateInfo() {
        const model = editor.getModel();
        document.getElementById('total-lines').textContent = model.getLineCount();
        document.getElementById('total-chars').textContent = model.getValue().length;
        document.getElementById('is-modified').textContent = '是';
    }

    // 初始化
    initEditor();

    // 从URL读取 userId 并自动填充
    (function autoInitFromUrl(){
        try {
            const params = new URLSearchParams(window.location.search);
            const uid = params.get('userId');
            if (uid) {
                const input = document.getElementById('workspace-userid');
                if (input) input.value = uid;
                addActionLog(`从URL载入用户ID：${uid}`);
            }
        } catch(e) {}
        loadFileTree().catch(console.error);
    })();

    // 代码执行相关函数
    function loadDetailedExample() {
        console.log('loadDetailedExample 函数被调用');
        console.log('当前语言:', currentLanguage);
        
        if (!editor) {
            console.error('编辑器未初始化');
            alert('编辑器未初始化，请刷新页面重试');
            return;
        }
        
        const code = detailedExamples[currentLanguage] || detailedExamples['python'];
        console.log('加载的示例代码:', code);
        
        if (code) {
            editor.setValue(code);
            addActionLog(`加载了${currentLanguage}示例代码`);
            console.log('示例代码已加载到编辑器');
        } else {
            console.error('未找到对应语言的示例代码');
        }
    }

    function clearExecutionResult() {
        document.getElementById('execution-result').innerHTML = '';
        document.getElementById('execution-status').style.display = 'none';
        addActionLog('清空了执行结果');
    }

    async function runCode() {
        console.log('runCode 函数被调用');
        
        if (!editor) {
            console.error('编辑器未初始化');
            alert('编辑器未初始化，请刷新页面重试');
            return;
        }
        
        const code = editor.getValue();
        console.log('获取到的代码:', code);
        
        const runBtn = document.getElementById('run-code-btn');
        const status = document.getElementById('execution-status');
        const result = document.getElementById('execution-result');
        
        if (!runBtn || !status || !result) {
            console.error('未找到必要的DOM元素:', { runBtn, status, result });
            return;
        }

        if (!code.trim()) {
            alert('请输入代码');
            return;
        }

        // 显示运行状态
        runBtn.disabled = true;
        runBtn.textContent = '⏳ 运行中...';
        status.style.display = 'block';
        status.className = 'execution-status loading';
        status.textContent = '正在执行代码，请稍候...';
        result.innerHTML = '';

        try {
            const response = await fetch('/api/run/advanced', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    code: code,
                    language: currentLanguage,
                    userId: getUserId(),
                    stdin: document.getElementById('stdin-input')?.value || ''
                })
            });

            const data = await response.json();
            
            if (data.success) {
                status.className = 'execution-status success';
                status.textContent = '代码执行成功！';
                addActionLog(`代码执行成功，输出：${data.output ? data.output.substring(0, 30) + '...' : '无输出'}`);
                
                result.innerHTML = `
                    <div class="result-success">
                        <strong>执行结果:</strong>
                        ${data.output || '代码执行完成，无输出'}
                    </div>
                    ${data.containerId ? `<div class="container-info">容器ID: ${data.containerId}</div>` : ''}
                `;
            } else {
                status.className = 'execution-status error';
                status.textContent = '代码执行失败！';
                addActionLog(`代码执行失败：${data.error || '未知错误'}`);
                
                result.innerHTML = `
                    <div class="result-error">
                        <strong>执行错误:</strong>
                        ${data.error || '未知错误'}
                    </div>
                `;
            }
        } catch (error) {
            status.className = 'execution-status error';
            status.textContent = '网络错误或服务器异常！';
            addActionLog(`网络错误：${error.message}`);
            
            result.innerHTML = `
                <div class="result-error">
                    <strong>错误信息:</strong>
                    ${error.message}
                </div>
            `;
        } finally {
            // 恢复按钮状态
            runBtn.disabled = false;
            runBtn.textContent = '▶️ 运行代码';
        }
    }

    // 响应式布局
    window.addEventListener('resize', function() {
        if (editor) editor.layout();
    });
}); 